/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

/**
 * @description 发送请求
 * @author aokunsang
 * @date 2013-1-6
 */
public final class Httptear {
	
	final static String UTF_8 = "utf-8";
	
	/**
	 * 请求JSON数据
	 * @param keys   所有KEY值                         如：String[]{"error","message"}
	 * @param values 对应KEY值的VALUE值            Object[]{404,"找不到页面."}
	 * @param response
	 * @throws IOException 
	 */
	public static void Output_json(String[] keys,Object[] values,HttpServletResponse response){
		StringBuilder sb = new StringBuilder("{");
		for(int i=0;i<keys.length;i++){   //{"error":404,"message":"11"}
			if(i>0) sb.append(",");
			boolean isNum = values[i] instanceof Number;
			sb.append("\"").append(keys[i]).append("\":");
			if(!isNum) sb.append("\"");
			sb.append(values[i]);
			if(!isNum) sb.append("\"");
		}
		sb.append("}");
		print(sb.toString(), response);
	}
	
	/**
	 * 请求JSON数据
	 * @param result
	 * @param response
	 * @throws IOException 
	 */
	public static void ResponseResultByUTF8(String result,HttpServletResponse response){
		print(result, response);
	}
	
	/**
	 * 请求编码过的JSON数据
	 * @param result
	 * @param response
	 * @throws IOException 
	 */
	public static void ResponseResultByUTF8ForEscape(String result,HttpServletResponse response) {
		print(Escape.escape(result), response);
	}
	
	/**
	 * 输出信息到浏览器
	 * @param message
	 * @param response
	 * @throws IOException 
	 */
	public static void print(String message,HttpServletResponse response){
		response.setHeader("ContentType","application/json;charset="+UTF_8);
		response.setHeader("Charset",UTF_8);
		response.setCharacterEncoding(UTF_8);
		try {
			response.getWriter().print(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
